<script setup lang="ts">
import type { FormInstance } from 'element-plus'
import { defaultFormData } from './index'
import type {
  EnergyDiscountInfo,
  SaveOrUpdateIndicatorParams,
} from '@/types'
import { energyDiscountApi, indicatorApi } from '@/api'
import CustomDialog from '@/components/CustomDialog/CustomDialog.vue'

import { useMixinQueryIndicatorDicts } from '@/mixins/MixinQueryIndicatorDicts'

const props = defineProps<{
  pointTreeData: any[]
  modalTitle: string
  unitData: any[]
  pointInfo: any
}>()
const emits = defineEmits<{
  'save-success': []
}>()

const formData = defineModel<SaveOrUpdateIndicatorParams>({
  default: () => defaultFormData,
})

const [energyDiscountData, setEnergyDiscountData]
  = useState<EnergyDiscountInfo[]>([])

const rules = {
  pointId: [{ required: true, message: '必填项' }],
  indicatorName: [{ required: true, message: '必填项' }],
  indicatorCode: [{ required: true, message: '必填项' }],

  indicatorType: [{ required: true, message: '必填项' }],
  measuringPointNumber: [
    { required: true, message: '必填项' },
  ],

  unitId: [{ required: true, message: '必填项' }],
  indicatorMultiple: [{ required: true, message: '必填项' }],
  // isVirtually: [{ required: true, message: '必填项' }],
  // energyId: [{ required: true, message: '必填项' }]
}

const inputable = ref(false)
watch(
  () => unref(inputable),
  () => {
    unref(formData).indicatorName = ''
  },
)

const { indicatorDicts, getIndicatorDicts, getKeyFromValue }
  = useMixinQueryIndicatorDicts()

/** 指标类别与统计类型的联动 */
const statisticalType = computed(() => {
  const { indicatorType } = toValue(formData)
  if (!indicatorType) {
    return ''
  }
  // 指标类型为 "用量" 时，统计类型为 "累加"
  return Number(indicatorType) === 1 ? '1' : '2'
})
/** 指标类别与虚拟指标的联动 */
const virtually = computed(() => {
  const { indicatorType } = toValue(formData)
  // 只有指标类型为 "用量" 时，才可能存在 "虚拟指标"
  return Number(indicatorType) === 1
})
/**
 * 虚拟指标没有单位、倍率、能源品种
 * 统计类型为“表头”没有倍率、能源品种，即指标类别是非用量
 */

const formRef = ref<FormInstance>()
const dialogRef = ref<InstanceType<
  typeof CustomDialog
> | null>(null)

function handlerMeasuringPointNumber(val: string) {
  formData.value.indicatorNumber = `${props.pointInfo?.pointCode}.${val}`
}
async function getEnergyDiscountData() {
  try {
    const { data: res }
      = await energyDiscountApi.queryList()
    if (!res) {
      setEnergyDiscountData([])
      return
    }
    setEnergyDiscountData(res)
  }
  catch (e) {}
}

async function clickSave(done: () => void) {
  try {
    const isValid = await formRef.value
      ?.validate()
      .catch(() => {})

    if (!isValid)
      return
    const params = {
      ...toValue(formData),
      statisticalType: statisticalType.value,
      statisticalName: ['', '累加', '表头'][
        +statisticalType.value
      ],
    }
    if (!params.id) {
      params.source = 0
    }
    // @ts-expect-error
    delete params.indicatorTypeName

    const { code }
      = await indicatorApi.saveOrUpdateIndicator(params)
    if (code === 200) {
      ElMessage.success('保存成功')
      done()
      close()
      emits('save-success')
    }
  }
  catch (e) {
  }
  finally {
    done()
  }
}
function handleUnitChange() {
  const unitList = props.unitData
    .map(item => item.unitList)
    .flat()
  const unit = unitList.find(
    item => item.id === formData.value.unitId,
  )
  if (!unit)
    return
  formData.value.unit = unit.unitName
}

function handleIndicatorNameChange(val: any) {
  if (val) {
    const key = getKeyFromValue(val)
    if (key) {
      formData.value.measuringPointNumber = key
    }
  }
}

watch(
  () => unref(formData).measuringPointNumber,
  (val: string) => {
    handlerMeasuringPointNumber(val || '')
  },
)

function open() {
  dialogRef.value?.open()
}
function close() {
  dialogRef.value?.close()
}

onMounted(() => {
  // 接口将废弃
  // getEnergyDiscountData();
  getIndicatorDicts()
})

defineExpose({
  open,
  close,
})
</script>

<template>
  <CustomDialog
    ref="dialogRef"
    width="640px"

    :title="modalTitle"
    need-saving no-scroll
    @confirm="clickSave"
  >
    <ElForm
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="140px"
    >
      <!-- <ElDivider>基本信息</ElDivider> -->
      <ElFormItem label="用能单元" prop="pointId">
        <ElCascader
          v-model="formData.pointId"
          :options="pointTreeData"
          :props="{
            value: 'id',
            label: 'pointName',
            children: 'children',
            checkStrictly: true,
            emitPath: false,
          }"
          disabled
          clearable
          placeholder="请选择用能单元"
          style="width: 100%"
        />
      </ElFormItem>
      <ElFormItem label="指标名称" prop="indicatorName">
        <IndicatorNamePicker
          v-model="formData.indicatorName"
          placeholder="请选择或输入指标名称"
          :options="indicatorDicts"
          class="w-full"
          @change="(val: any) => handleIndicatorNameChange(val)"
        />
      </ElFormItem>
      <ElFormItem
        label="测点编码"
        prop="measuringPointNumber"
      >
        <ElInput
          v-model.trim="formData.measuringPointNumber"
          maxlength="50"
          placeholder="请输入测点编码"
          clearable
        />
      </ElFormItem>
      <ElFormItem label="指标编码">
        <ElInput
          v-model.trim="formData.indicatorNumber"
          maxlength="50"
          placeholder="请输入指标编码"
          disabled
          clearable
        />
      </ElFormItem>
      <ElFormItem label="测点点位号" prop="indicatorCode">
        <ElInput
          v-model.trim="formData.indicatorCode"
          placeholder="请输入测点点位号"
        />
      </ElFormItem>
      <!-- <ElDivider>类型</ElDivider>
      <ElFormItem label="指标类别" prop="indicatorType">
        <DictionaryPicker
          v-model="formData.indicatorType"
          code="ZHI_BIAO_LEI_BIE"
          placeholder="请选择指标类别"
        ></DictionaryPicker>
      </ElFormItem>
      <ElFormItem v-if="statisticalType" label="统计类型">
        <DictionaryPicker
          disabled
          code="TONG_JI_LEI_XING"
          :model-value="statisticalType"
        ></DictionaryPicker>
      </ElFormItem> -->
      <!-- <ElFormItem
        v-if="virtually"
        label="是否虚拟类型"
        prop="isVirtually"
      >
        <ElRadioGroup v-model="formData.isVirtually">
          <ElRadio :label="0" border>否</ElRadio>
          <ElRadio :label="1" border>是</ElRadio>
        </ElRadioGroup>
      </ElFormItem> -->
      <!-- <template
        v-if="formData.isVirtually === 0 || !virtually"
      > -->
      <!-- <template v-if="!virtually">
        <ElDivider>参数</ElDivider>
        <ElFormItem
          v-if="statisticalType !== '2'"
          label="能源品种"
          prop="energyId"
        >
          <ElSelect
            v-model="formData.energyId"
            filterable
            placeholder="请选择能源品种"
            class="width-fill"
          >
            <ElOption
              v-for="item in energyDiscountData"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
              <span style="float: left">
                {{ item.name }}
              </span>
              <span
                style="
                  float: right;
                  color: var(--el-text-color-secondary);
                  font-size: 13px;
                "
              >
                {{
                  item.discountFactor ||
                  item.referenceCoefficient
                }}
              </span>
            </ElOption>
          </ElSelect>
        </ElFormItem>
      </template> -->
      <ElFormItem label="单位" prop="unitId">
        <el-cascader
          v-model="formData.unitId"
          :options="unitData"
          :props="{
            label: 'unitName',
            value: 'id',
            children: 'unitList',
            emitPath: false,
          }"
          class="width-fill"
          @change="handleUnitChange"
        />
      </ElFormItem>
      <ElFormItem label="倍率" prop="indicatorMultiple">
        <ElInputNumber
          v-model="formData.indicatorMultiple"
          :min="1"
          :max="100000"
          :step="1"
          step-strictly
          style="width: 160px;"
        />
      </ElFormItem>
    </ElForm>
  </CustomDialog>
</template>
